//
//  FieldObservationViewController.m
//  Tazama NGO
//
//  Created by jsheriff on 3/7/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "FieldObservationViewController.h"
#import "TextEditViewReadOnlyController.h"
#import "GeoRefCustomCell.h"
#import "Notifications.h"

#define kGeneralSection 0
#define kObservationTextSection 1
#define kGeorefSection 2
#define kImageSection 3

@implementation FieldObservationViewController

@synthesize fieldObservation;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"Field Obsrvn";
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == kGeneralSection)
		return 3;
	else if (section == kObservationTextSection)
		return 1;
	else if (section == kGeorefSection)
		return 1;
    else if (section == kImageSection)
        return 1;
	else
		return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title = @"";
	
	if (section == kObservationTextSection)
		title = @"Observation";
	else if (section == kGeorefSection)
		title = @"Georef";
    else if (section == kImageSection)
        title = @"Image";
	
	return title;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.section == kImageSection)
        return 120;
    else
        return 46;
}

-(UITableViewCell *)getCell:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"FieldObservationGeneralCell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:cellIdentifier] autorelease];
	}	
	
	cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:18];
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	
	return cell;
}

-(UITableViewCell *)getCellObservationText:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"FieldObservationObservationTextCell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
	}	
	
	cell.textLabel.font = [UIFont systemFontOfSize:16];
	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	
	return cell;
}

-(GeoRefCustomCell *)getCellGeoref:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"FieldObservationGeorefCell";
	
	GeoRefCustomCell *cell = (GeoRefCustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[GeoRefCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier mapButton:YES] autorelease];
	}
	
	[cell.mapButton addTarget:self action:@selector(clickMapButton:) forControlEvents:UIControlEventTouchUpInside];
	
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
	return cell;
}

-(UITableViewCell *)getCellImage:(UITableView *)tableView
{
	static NSString *cellIdentifier = @"EventDetailCellImage";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier] autorelease];
	}	
	
	cell.textLabel.font = [UIFont systemFontOfSize:16];
	
	return cell;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	NSUInteger row = [indexPath row];
	NSUInteger section = [indexPath section];
	
	UITableViewCell *cell;
	
	if (section == kGeneralSection)
	{
		if (row == 0) {
			cell = [self getCell:tableView];
			cell.textLabel.text = @"Needs";
			cell.detailTextLabel.text = fieldObservation.immediateNeeds;
		}
		else if (row == 1) {
			cell = [self getCell:tableView];
			cell.textLabel.text = @"Confidence";
			cell.detailTextLabel.text = [fieldObservation.confidence capitalizedString];
//            NSObject *object = fieldObservation;
//            cell.detailTextLabel.text = [[object valueForKey:@"confidence"] capitalizedString];
		}
		else if (row == 2) {
			cell = [self getCell:tableView];
			cell.textLabel.text = @"Severity";
			cell.detailTextLabel.text = [fieldObservation.severity capitalizedString];
		}
	}
	else if (section == kObservationTextSection)
	{
		cell = [self getCellObservationText:tableView];
		cell.textLabel.text = fieldObservation.observationText;
	}
	else if (section == kGeorefSection)
	{
		GeoRefCustomCell *geoRefCell = [self getCellGeoref:tableView];
		//  \xC2\xB0 is a degree symbol
		geoRefCell.latitudeLabel.text = [NSString stringWithFormat:@"Lat %2.4f\xC2\xB0", fieldObservation.location.latitude];		
		geoRefCell.longitudeLabel.text = [NSString stringWithFormat:@"Lon %3.4f\xC2\xB0", fieldObservation.location.longitude];	
		cell = geoRefCell;
	}
    else if (section == kImageSection)
	{
        cell = [self getCellImage:tableView];

        if (fieldObservation.image != nil) {
            UIGraphicsBeginImageContext( CGSizeMake(108, 108) );
            [fieldObservation.image drawInRect:CGRectMake( 0, 0, 108, 108)];
            UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            cell.imageView.image = thumbnail;
//            [thumbnail release];
        }
        else
        {
            UIImage *noImage = [UIImage imageNamed:@"NoImage.PNG"];
            cell.imageView.image = noImage;
        }
		
//        cell.imageView.layer.cornerRadius = 5.0;
//        cell.imageView.layer.masksToBounds = YES;
			
//        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
//        [dateFormat setDateFormat:@"dd MMM yy HHmm"];
//        cell.detailTextLabel.text = [dateFormat stringFromDate:logEntry.Timestamp];
//        [dateFormat release];
			
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}

	return cell;
}

- (IBAction)clickMapButton:(id)sender {
	NSDictionary *userInfo = [NSDictionary dictionaryWithObject:fieldObservation forKey:kFieldObservationKey];
	[[NSNotificationCenter defaultCenter] postNotificationName:kDisplayMessageOnMapNotification object:self userInfo:userInfo];		
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.section == kObservationTextSection && indexPath.row == 0) {
		TextEditViewReadOnlyController *viewController = [[TextEditViewReadOnlyController alloc] initWithNibName:@"TextEditViewReadOnlyController" bundle:nil];
		viewController.title = @"Obsrvn Text";
		viewController.text = fieldObservation.observationText;
		[self.navigationController pushViewController:viewController animated:YES];
		[viewController release];
		
	}
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

